package operation;

import abbot.finder.BasicFinder;
import abbot.finder.ComponentNotFoundException;
import abbot.finder.MultipleComponentsFoundException;
import abbot.finder.matchers.ClassMatcher;
import abbot.tester.JFileChooserTester;
import robotCross.CrossJFileChooserTester;
import robotCross.TipMatcher;
import util.Info;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.util.ArrayList;


public class JFileChooserOperation extends Operation {
	JDialog dialog = null;
	JFileChooser fileChooser = null;

	public JFileChooserOperation(int waitTime) throws Exception {
		fileChooser = new CommonOperation().waitForJFileChooserDisplay(waitTime);
	}

	public JFileChooserOperation() {
		fileChooser = this.findJFileChooser();
	}

	public JFileChooserOperation(JFileChooser jFileChooser) {
		this.fileChooser = jFileChooser;
	}

	public JFileChooser findJFileChooser() {
		dialog = (JDialog) KeyboardFocusManager
				.getCurrentKeyboardFocusManager().getFocusedWindow();
		JFileChooser fileChooser = null;
		try {
			fileChooser = (JFileChooser) new BasicFinder().find(dialog,
					new ClassMatcher(JFileChooser.class));
		} catch (ComponentNotFoundException | MultipleComponentsFoundException e) {
			// TODO Auto-generated catch block
			if (e instanceof MultipleComponentsFoundException) {
				e.printStackTrace();
			}
		}
		this.fileChooser = fileChooser;
		return fileChooser;
	}

	/**
	 * 选择文件
	 *
	 * @param readOnly 是否只读打开
	 */
	public Object chooseFile(String filePath, boolean readOnly) throws Exception {
		JFileChooserTester chooserTester = new CrossJFileChooserTester();
		File file = new File(filePath);
		if (!file.exists()) {
			Info.out("文件不存在：" + file);
			throw new Exception("文件不存在：" + file);
		}
		Operation.robot.delay(1000);
		chooserTester.actionSetSelectedFile(fileChooser, file);
		Operation.robot.delay(1000);
//		if (!fileChooser.getSelectedFile().getName().equals(file.getName())) {
			chooserTester.actionSetFilename(fileChooser, file.getName());
//		}
		Operation.robot.delay(1000);
		JCheckBox checkBox = null;
		if (readOnly) {
			checkBox = (JCheckBox) new BasicFinder().find(fileChooser,
					new ClassMatcher(JCheckBox.class));
			super.clickComponent(checkBox);
		}
		chooserTester.actionApprove(fileChooser);
		return fileChooser;
	}


	/**
	 * 选择文件
	 *
	 */
	public Object chooseFile(String filePath) throws Exception {
		//默认将共享数据源只读打开
		if (filePath.startsWith("\\\\") && (filePath.toLowerCase().endsWith("udb")||filePath.toLowerCase().endsWith("udd"))) {
			return this.chooseFile(filePath, false);//fixme:这里应该是true，但是现在没有只读控件
		}
		return this.chooseFile(filePath, false);
	}

	/**
	 * 选择目录
	 *
	 * @param makeDir  目录不存在时是否新建目录
	 */
	public Object chooseDir(String filePath, boolean makeDir) {
		JFileChooserTester chooserTester = new CrossJFileChooserTester();
		File file = new File(filePath);
		if (!file.exists()) {
			if (makeDir) {
				boolean mkdirs = file.mkdirs();
				if (!mkdirs) {
					Info.out("目录创建失败：" + file);
					return fileChooser;
				}
			} else {
				Info.out("目录不存在，且未设置创建目录：" + file);
				return fileChooser;
			}
		}
		Operation.robot.delay(500);
		chooserTester.actionSetDirectory(fileChooser, filePath);
		Operation.robot.delay(500);
		chooserTester.actionApprove(fileChooser);
		return dialog;
	}

	/**
	 * 选择文件
	 *
	 * @param filePath
	 * @return
	 */
	public Object createFile(String filePath, boolean makeDir) throws ComponentNotFoundException, MultipleComponentsFoundException {
		File file = new File(filePath);
		String dirPath = file.getParent();
		JFileChooserTester chooserTester = new CrossJFileChooserTester();
		this.chooseDir(dirPath, makeDir);
		Operation.robot.delay(1000);
		chooserTester.actionSetFilename(fileChooser, file.getName());
		Operation.robot.delay(1000);
		chooserTester.actionApprove(fileChooser);
		//覆盖提示不一定弹出，不能因此抛出异常导致用例失败。
		try {
			new DialogOperation().clickComponent(new TipMatcher("确定"));
		} catch (ComponentNotFoundException e) {
//			e.printStackTrace();
		} catch (MultipleComponentsFoundException e) {
//			e.printStackTrace();
		}
		new DialogOperation().WaitForWindowDispose(60000);
		return dialog;
	}

	//============批量选择文件===================
	public Object chooseFiles(String fileDir, String[] fileNames, boolean readOnly) {
		ArrayList<File> files = new ArrayList<>();
		for (String fileName : fileNames) {
			File file = new File(fileDir + "\\" + fileName);
			if (file.exists() && new File(file.getParent()).equals(new File(fileDir))) {
				files.add(file);
			} else {
				Info.out("文件" + file.getName() + "不存在于：" + fileDir);
			}
		}
		if (files.size() > 0) {
			return this.chooseFiles(fileDir, files.toArray(new File[files.size()]), readOnly);
		}
		return fileChooser;
	}

	public Object chooseFiles(String[] filePaths, boolean readOnly) {
		if (filePaths != null && filePaths.length > 0) {
			File[] files = new File[filePaths.length];
			for (int i = 0; i < filePaths.length; i++) {
				files[i] = new File(filePaths[i]);
			}
			return chooseFiles(files, readOnly);
		}
		return fileChooser;
	}

	public Object chooseFiles(File[] files, boolean readOnly) {
		if (files != null && files.length > 0) {
			String parent = files[0].getParent();
			return this.chooseFiles(parent, files, readOnly);
		}
		return fileChooser;
	}

	public Object chooseFiles(String fileDir, File[] files, boolean readOnly) {
		this.chooseDir(fileDir, false);
		CrossJFileChooserTester crossJFileChooserTester = new CrossJFileChooserTester();
		if (files != null && files.length > 0) {
			crossJFileChooserTester.actionSetSelectedFiles(fileChooser, files);
		}
		JCheckBox checkBox = null;
		if (readOnly) {
			try {
				checkBox = (JCheckBox) new BasicFinder().find(fileChooser,
						new ClassMatcher(JCheckBox.class));
			} catch (ComponentNotFoundException | MultipleComponentsFoundException e) {
				if (e instanceof MultipleComponentsFoundException) {
					e.printStackTrace();
				}
			}
			super.clickComponent(checkBox);
		}
		Operation.robot.delay(500);
		crossJFileChooserTester.actionApprove(fileChooser);
		return fileChooser;
	}
	/**
	 * 创建目录
	 * @param dirPath 目录位置
	 * @return
	 */
	public void createDir(String dirPath){
		File file = new File(dirPath);
		if(!file.exists()){
			file.mkdirs();
			if(!file.exists()) {
				Info.out("目录创建失败：" + file);
			}
		}

	}

	/**
	 * 保存文件
	 * @param filePath 文件路径
	 * @return
	 */
	public void saveFile(String filePath){
		File file = new File(filePath);
		String dirPath = file.getParent();
		createDir(dirPath);
		if(file.exists()){
			file.delete();
		}
		JFileChooserTester chooserTester = new CrossJFileChooserTester();
		chooserTester.actionSetSelectedFile(fileChooser, file);
		Operation.robot.delay(1000);
		chooserTester.actionSetFilename(fileChooser, file.getName());
		Operation.robot.delay(1000);
		chooserTester.actionApprove(fileChooser);
	}

}
